<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-button type="primary" size="small" @click="showAddRolesDialogVisible = true">添加角色</el-button>

      <el-table :data="rolesList" border stripe fit>
        <!--<el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!~~ 渲染一级权限 ~~>
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!~~ 渲染二级和三级权限 ~~>
              <el-col :span="19">
                <!~~ 通过 for 循环嵌套渲染二级权限 ~~>
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>-->
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName" align="center"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc" align="center"></el-table-column>
        <el-table-column label="创建时间" prop="create_time" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="update_time" align="center">
          <template slot-scope="scope">
            {{ scope.row.updateTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template slot-scope="scope">
            <el-button @click="showEditDialog(scope.row.id)" size="mini" type="primary" icon="el-icon-edit"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRolesById(scope.row.id)"></el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="showAddRolesDialogVisible" width="50%" @close="rolesDialogClosed">
      <el-form :model="rolesInfo" :rules="rolesInfoRules" ref="addRolesInfoRef" label-width="110px">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="rolesInfo.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="rolesInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色信息对话框 -->
    <el-dialog @close="rolesDialogClosed" title="修改角色信息" :visible.sync="editRolesDialogClosed" width="50%">
      <el-form :model="rolesInfo" :rules="rolesInfoRules" ref="editRolesInfoRef" label-width="110px">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="rolesInfo.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="rolesInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogClosed = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="showSetRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  postRoles,
  getAllRights,
  postRolesRights,
  delRolesRights,
  getRolesInfoById,
  putEditRolesInfo,
  deleteRolesById
} from '@/api/roles'

export default {
  name: 'roles',
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制分配权限对话框的显示与隐藏
      showSetRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点 id 值数组
      defKeys: [],
      // 当前即将分配权限的角色 id
      roleId: '',
      // 添加角色信息
      rolesInfo: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      // 控制新增角色对话框的显示与隐藏
      showAddRolesDialogVisible: false,
      rolesInfoRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      // 控制修改用户信息对话框的展示和隐藏
      editRolesDialogClosed: false
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //获取所有角色列表
    async getRolesList() {
      const res = await getRoles()
      if (res.meta.status === 200) {
        this.rolesList = res.data
      } else {
        this.$message.error('获取角色列表失败')
      }
    },

    // 新增角色
    async addRoles() {
      const res = await postRoles(this.rolesInfo)
      if (res.meta.status === 201) {
        this.$message.success(res.meta.msg)
        this.showAddRolesDialogVisible = false
        this.getRolesList()
      } else {
        this.$message.error(res.meta.msg)
      }
    },

    // 监听新增、编辑角色对话框关闭事件
    rolesDialogClosed() {
      this.rolesInfo = {
        roleName: '',
        roleDesc: ''
      }
    },

    // 展示编辑用户信息的对话框
    async showEditDialog(id) {
      const res = await getRolesInfoById(id)
      if (res.meta.status === 200) {
        this.rolesInfo = res.data
        this.editRolesDialogClosed = true
      } else {
        this.$message.error(res.meta.msg)
      }
    },

    // 修改用户信息并提交
    editRolesInfo() {
      this.$refs.editRolesInfoRef.validate(async valid => {
        if (valid) {
          // 发起修改用户信息的网络请求
          const res = await putEditRolesInfo(this.rolesInfo)
          if (res.meta.status === 200) {
            // 关闭对话框
            this.editRolesDialogClosed = false
            // 刷新数据列表
            this.getRolesList()
            // 提示修改成功
            this.$message.success(res.meta.msg)
          } else {
            return this.$message.error(res.meta.msg)
          }
        }
      })
    },

    // 根据 id 删除对应的角色
    async delRolesById(id) {
      // 弹框询问用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      if (confirmResult === 'confirm') {
        const res = await deleteRolesById(id)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          this.getRolesList()
        } else {
          this.$message.error(res.meta.msg)
        }
      }
    },

    // 根据 id 删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'confirm') {
        let params = {
          roleId: role.id,
          rightId: rightId
        }
        const res = await delRolesRights(params)
        if (res.meta.status === 200) {
          role.children = res.data
        } else {
          this.$message.error('删除权限失败')
        }
      } else {
        this.$message.info('已取消删除')
      }
    },

    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限数据
      let params = {
        type: 'tree'
        // type: 'list'
      }
      const res = await getAllRights(params)
      if (res.meta.status === 200) {
        // 获取到的权限数据的保存
        this.rightsList = res.data
        // 递归获取三级节点的 id
        this.getLeafKeys(role, this.defKeys)
        this.showSetRightDialogVisible = true
      } else {
        this.$message.error('获取权限数据失败')
      }
    },

    // 通过递归的形式，获取角色下所有三级权限的 id ，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包括 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },

    // 监听分配权限对话框关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },

    // 点击为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      let params = {
        roleId: this.roleId,
        rids: idStr
      }
      const res = await postRolesRights(params)
      if (res.meta.status === 200) {
        this.$message.success('分配权限成功')
        this.getRolesList()
        this.showSetRightDialogVisible = false
      } else {
        this.$message.error('分配权限失败')
      }
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
